<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" th:replace="~{common/base :: layout(~{::title}, ~{::content}, ~{::style}, ~{::script})}">
<head>
    <title th:text="${product != null ? product.name + ' - 优选商城' : '商品详情 - 优选商城'}">商品详情 - 优选商城</title>
    <style>
        .product-image {
            max-height: 400px;
            object-fit: contain;
        }
        .product-thumb {
            width: 80px;
            height: 80px;
            object-fit: cover;
            cursor: pointer;
            border: 2px solid transparent;
            transition: border-color 0.2s;
        }
        .product-thumb.active {
            border-color: #0d6efd;
        }
        .quantity-control {
            width: 120px;
        }
        .product-detail {
            padding: 20px 0;
        }
        .product-price {
            font-size: 1.8rem;
            color: #dc3545;
        }
        .related-products {
            padding: 40px 0;
            background-color: #f8f9fa;
            margin-top: 40px;
        }
        .related-product-card {
            border: none;
            transition: all 0.3s ease;
            margin-bottom: 20px;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            height: 100%;
        }
        .related-product-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        .related-product-image {
            height: 180px;
            object-fit: cover;
        }
        .related-product-title {
            font-size: 1rem;
            height: 42px;
            overflow: hidden;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
        }
        .breadcrumb {
            background: #f8f9fa;
            padding: 12px 20px;
            border-radius: 8px;
        }
        .product-detail img {
            max-width: 100%;
            height: auto;
        }
    </style>
</head>
<body>
    <div th:fragment="content">
        <div class="container mt-4">
            <!-- 面包屑导航 -->
            <nav aria-label="breadcrumb" class="mb-4">
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="/">首页</a></li>
                    <li class="breadcrumb-item" th:if="${product != null && product.category != null}">
                        <a th:href="@{/category/{id}(id=${product.categoryId})}" th:text="${product.category.name}">商品分类</a>
                    </li>
                    <li class="breadcrumb-item active" aria-current="page" th:text="${product != null ? product.name : '商品详情'}">商品详情</li>
                </ol>
            </nav>
            
            <div class="row" th:if="${product != null}">
                <!-- 商品图片展示 -->
                <div class="col-md-6 mb-4">
                    <div class="card border-0 shadow-sm p-3 mb-3">
                        <div class="text-center">
                            <img th:src="${product.mainImage}" id="mainProductImage" class="img-fluid product-image" alt="商品图片">
                        </div>
                    </div>
                    <div class="d-flex justify-content-center" th:if="${product.subImages != null}">
                        <div class="d-flex overflow-auto">
                            <img th:src="${product.mainImage}" class="product-thumb active me-2 rounded" 
                                 onclick="changeImage(this.src)" alt="主图">
                            <th:block th:each="image : ${#strings.arraySplit(product.subImages, ',')}">
                                <img th:if="${!#strings.isEmpty(image)}" th:src="${image}" class="product-thumb me-2 rounded" 
                                     onclick="changeImage(this.src)" alt="子图">
                            </th:block>
                        </div>
                    </div>
                </div>
                
                <!-- 商品信息 -->
                <div class="col-md-6">
                    <div class="card border-0 shadow-sm p-4">
                        <h2 th:text="${product.name}">商品名称</h2>
                        <p class="text-muted" th:text="${product.subtitle}">商品副标题</p>
                        <div class="d-flex align-items-center mb-3">
                            <span class="product-price">¥<span th:text="${#numbers.formatDecimal(product.price, 1, 2)}">0.00</span></span>
                            <span class="badge bg-danger ms-2">热销</span>
                        </div>
                        
                        <div class="d-flex justify-content-between mb-3 py-2 border-top border-bottom">
                            <div>
                                <i class="bi bi-box-seam text-muted"></i>
                                <span class="text-muted">库存: <span class="text-dark fw-bold" th:text="${product.stock}">0</span></span>
                            </div>
                            <div>
                                <i class="bi bi-graph-up text-muted"></i>
                                <span class="text-muted">销量: <span class="text-dark fw-bold" th:text="${product.sales}">0</span></span>
                            </div>
                            <div th:if="${product.category != null}">
                                <i class="bi bi-tag text-muted"></i>
                                <span class="text-muted">分类: <a th:href="@{/category/{id}(id=${product.categoryId})}" th:text="${product.category.name}">分类</a></span>
                            </div>
                        </div>
                        
                        <form id="addToCartForm" class="mb-4">
                            <div class="mb-3">
                                <label for="quantity" class="form-label">数量:</label>
                                <div class="input-group quantity-control">
                                    <button type="button" class="btn btn-outline-secondary" onclick="decreaseQuantity()">-</button>
                                    <input type="number" class="form-control text-center" id="quantity" name="quantity" value="1" min="1" th:max="${product.stock}">
                                    <button type="button" class="btn btn-outline-secondary" onclick="increaseQuantity()">+</button>
                                </div>
                            </div>
                            
                            <div class="d-grid gap-2">
                                <input type="hidden" id="productId" th:value="${product.id}">
                                <button type="button" class="btn btn-primary btn-lg" onclick="addToCart()">
                                    <i class="bi bi-cart-plus"></i> 加入购物车
                                </button>
                                <button type="button" class="btn btn-danger btn-lg" onclick="buyNow()">
                                    <i class="bi bi-lightning"></i> 立即购买
                                </button>
                            </div>
                        </form>
                        
                        <!-- 服务承诺 -->
                        <div class="mt-4">
                            <div class="d-flex flex-wrap">
                                <div class="me-3 mb-2">
                                    <i class="bi bi-check-circle-fill text-success"></i>
                                    <small>正品保障</small>
                                </div>
                                <div class="me-3 mb-2">
                                    <i class="bi bi-truck text-success"></i>
                                    <small>极速发货</small>
                                </div>
                                <div class="me-3 mb-2">
                                    <i class="bi bi-arrow-return-left text-success"></i>
                                    <small>7天无理由退换</small>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 商品详情 -->
            <div class="row mt-4" th:if="${product != null}">
                <div class="col-12">
                    <div class="card border-0 shadow-sm">
                        <div class="card-header bg-white">
                            <ul class="nav nav-tabs card-header-tabs" id="productTab" role="tablist">
                                <li class="nav-item" role="presentation">
                                    <button class="nav-link active" id="detail-tab" data-bs-toggle="tab" data-bs-target="#detail" type="button" role="tab" aria-controls="detail" aria-selected="true">商品详情</button>
                                </li>
                                <li class="nav-item" role="presentation">
                                    <button class="nav-link" id="params-tab" data-bs-toggle="tab" data-bs-target="#params" type="button" role="tab" aria-controls="params" aria-selected="false">规格参数</button>
                                </li>
                            </ul>
                        </div>
                        <div class="card-body">
                            <div class="tab-content" id="productTabContent">
                                <div class="tab-pane fade show active product-detail" id="detail" role="tabpanel" aria-labelledby="detail-tab">
                                    <div th:if="${product.detail != null && !#strings.isEmpty(product.detail)}" th:utext="${product.detail}">
                                        <p>商品详情内容</p>
                                    </div>
                                    <div th:if="${product.detail == null || #strings.isEmpty(product.detail)}" class="text-center py-5 text-muted">
                                        <i class="bi bi-info-circle" style="font-size: 2rem;"></i>
                                        <p class="mt-2">暂无详细信息</p>
                                    </div>
                                </div>
                                <div class="tab-pane fade" id="params" role="tabpanel" aria-labelledby="params-tab">
                                    <div class="table-responsive">
                                        <table class="table table-hover">
                                            <tbody>
                                                <tr>
                                                    <th scope="row" style="width: 30%;">品牌</th>
                                                    <td>优选品牌</td>
                                                </tr>
                                                <tr>
                                                    <th scope="row">商品名称</th>
                                                    <td th:text="${product.name}">商品名称</td>
                                                </tr>
                                                <tr>
                                                    <th scope="row">上架时间</th>
                                                    <td th:text="${#temporals.format(product.createTime, 'yyyy-MM-dd')}">上架时间</td>
                                                </tr>
                                                <tr th:if="${product.category != null}">
                                                    <th scope="row">商品分类</th>
                                                    <td th:text="${product.category.name}">分类名称</td>
                                                </tr>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 相关推荐商品 -->
            <div class="related-products mt-5" th:if="${product != null && relatedProducts != null && !relatedProducts.isEmpty()}">
                <div class="container">
                    <h3 class="mb-4">相关推荐</h3>
                    <div class="row">
                        <div class="col-md-3 col-6" th:each="relatedProduct : ${relatedProducts}">
                            <a th:href="@{/product/{id}(id=${relatedProduct.id})}" class="text-decoration-none">
                                <div class="card related-product-card">
                                    <img th:src="${relatedProduct.mainImage}" class="card-img-top related-product-image" th:alt="${relatedProduct.name}">
                                    <div class="card-body">
                                        <h5 class="card-title related-product-title" th:text="${relatedProduct.name}">商品名称</h5>
                                        <p class="card-text text-danger fw-bold" th:text="${'¥' + #numbers.formatDecimal(relatedProduct.price, 1, 2)}">¥0.00</p>
                                    </div>
                                </div>
                            </a>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 商品不存在提示 -->
            <div class="alert alert-warning" th:if="${product == null}">
                商品不存在或已下架，<a href="/" class="alert-link">返回首页</a>
            </div>
        </div>
    </div>

    <script th:fragment="script">
        function changeImage(src) {
            document.getElementById('mainProductImage').src = src;
            
            // 移除所有缩略图的active类
            document.querySelectorAll('.product-thumb').forEach(thumb => {
                thumb.classList.remove('active');
            });
            
            // 为当前点击的缩略图添加active类
            document.querySelectorAll('.product-thumb').forEach(thumb => {
                if (thumb.src === src) {
                    thumb.classList.add('active');
                }
            });
        }
        
        function decreaseQuantity() {
            const quantityInput = document.getElementById('quantity');
            let quantity = parseInt(quantityInput.value);
            if (quantity > 1) {
                quantityInput.value = quantity - 1;
            }
        }
        
        function increaseQuantity() {
            const quantityInput = document.getElementById('quantity');
            let quantity = parseInt(quantityInput.value);
            const maxQuantity = parseInt(quantityInput.getAttribute('max'));
            if (quantity < maxQuantity) {
                quantityInput.value = quantity + 1;
            } else {
                showToast('库存不足', 'danger');
            }
        }
        
        function addToCart() {
            const productId = document.getElementById('productId').value;
            const quantity = document.getElementById('quantity').value;
            
            // 发送AJAX请求
            $.ajax({
                url: '/cart/add',
                type: 'POST',
                data: {
                    productId: productId,
                    quantity: quantity
                },
                success: function(res) {
                    if (res.code === 0) {
                        showToast('已成功添加到购物车', 'success');
                    } else {
                        showToast(res.msg || '添加失败', 'danger');
                    }
                },
                error: function() {
                    showToast('请求失败，请重试', 'danger');
                }
            });
        }
        
        function buyNow() {
            const productId = document.getElementById('productId').value;
            const quantity = document.getElementById('quantity').value;
            
            // 发送AJAX请求创建订单
            $.ajax({
                url: '/order/create',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({
                    productId: parseInt(productId),
                    quantity: parseInt(quantity)
                }),
                success: function(res) {
                    if (res.code === 0) {
                        // 创建订单成功，跳转到支付页面
                        window.location.href = '/order/pay/' + res.data.orderNo;
                    } else {
                        showToast(res.msg || '创建订单失败', 'danger');
                    }
                },
                error: function(xhr, status, error) {
                    console.error('创建订单失败:', error);
                    showToast('请求失败，请重试', 'danger');
                }
            });
        }
        
        function showToast(message, type) {
            const toastContainer = document.querySelector('.toast-container');
            if (!toastContainer) return;
            
            const toast = document.createElement('div');
            toast.className = `toast align-items-center text-white bg-${type} border-0`;
            toast.setAttribute('role', 'alert');
            toast.setAttribute('aria-live', 'assertive');
            toast.setAttribute('aria-atomic', 'true');
            
            toast.innerHTML = `
                <div class="d-flex">
                    <div class="toast-body">
                        <i class="bi bi-${type === 'success' ? 'check-circle' : 'exclamation-circle'} me-2"></i>
                        ${message}
                    </div>
                    <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
                </div>
            `;
            
            toastContainer.appendChild(toast);
            const bsToast = new bootstrap.Toast(toast, {
                autohide: true,
                delay: 3000
            });
            
            bsToast.show();
            
            // 自动移除toast元素
            toast.addEventListener('hidden.bs.toast', function () {
                toast.remove();
            });
        }
    </script>
</body>
</html> 